import * as Router from 'koa-router';
import {dingTalkApi} from 'dingtalk-app';
import {menuModel} from './../model/menuModel'
import {homeModel} from './../model/homeModel'
let router = new Router();
router.prefix('/api/menu')

//添加模板名称
router.post('/save', async (ctx: any) => {
    const {name} = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    let result = await menuModel.create({name: name, user: user, json: []})
    ctx.body = {code:100}
})

//查看所有模板
router.post('/listAll', async (ctx: any) => {
    const res = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    const findList = await menuModel.find().sort({createDate: -1})
    ctx.body = {code:100, data: findList}
})

//根据主键修改 模板
router.post('/findById', async (ctx: any) => {
    const {_id} = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    let result = await menuModel.findOne({_id: _id})
    ctx.body = {code:100, data: result}
})

//根据主键修改 模板
router.post('/updateById', async (ctx: any) => {
    const res = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    await menuModel.update({_id: res._id},res)
    ctx.body = {code:100}
})

//根据主键修改 模板
router.post('/updateName', async (ctx: any) => {
    const {_id, name} = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    await menuModel.update({_id: _id},{name: name})
    ctx.body = {code:100}
})

//根据主键修改 模板
router.post('/delById', async (ctx: any) => {
    const {_id} = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    await menuModel.remove({_id: _id})
    ctx.body = {code:100}
})

//激活首页
router.post('/active', async (ctx: any) => {
    const res = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    const findList = await homeModel.find();
    if(findList.length > 0){
        const {_id} = findList[0];
        await homeModel.update({_id: _id}, {json: res.json,back: res.back, name: res.name, user: user}, {upsert: false})
    }else{
        await homeModel.create(res)
    }
    ctx.body = {code:100}
})

//查找首页
router.post('/findHome', async (ctx: any) => {
    const res = ctx.request.body;
    let authorization :any = ctx.header.authorization;
    let user = dingTalkApi.decode(authorization)
    const findList = await homeModel.find();
    ctx.body = {code:100, data: findList}
})



export default router;
